<?php

/**
 * sfWidgetFormTextareaReloaded extends sfWidgetFormTextarea for adding real time input text counter
 */
class sfWidgetFormTextareaReloaded extends sfWidgetFormTextarea
{
  /**
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetFormTextarea
   */
  protected function configure($options = array(), $attributes = array())
  {
    $this->addOption('max_length');
    $this->addOption('type', 'textarea');
    $this->addOption('mask', '(%current% / %total% characters)');
    parent::configure();
  }

  /**
   * @param  string $name        The element name
   * @param  string $value       The value displayed in this widget
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
      $textarea = $this->renderContentTag('textarea', self::escapeOnce($value), array_merge(array('name' => $name), $attributes));
      if($this->getOption('max_length')) $textarea .= $this->getCounter($this->generateId($name), $value);
      return $textarea;
  }

  /**
   * Returns HTML/Javascript to count the widget input text length
   * @param  string  $id     Id of the target widget
   * @param  string  $value  Current Widget value
   * @return string
   */
  private function getCounter($id, $value){
      $total = $this->getOption('max_length');
      $current = strlen($value);
      $left  = $total - $current;
      $replace = array('%total%' => '<span class="total">'.$total.'</span>', '%left%' => '<span class="left">'.$left.'</span>', '%current%' => '<span class="current">'.$current.'</span>');
      $mask = $this->getOption('mask');
      $html = '<p id="'.$id.'_counter" class="textarea-counter">'.$this->translate($mask, $replace).'</p>';
      $js  = '
      <script type="text/javascript" language="javascript">
          (function(){
              var widget  = $("#'.$id.'");
              var counter = $("#'.$id.'_counter");
              var total   = counter.find(".total");
              var left    = counter.find(".left");
              var current = counter.find(".current");

              var totalCharacters = '.$total.';

              widget.keypress(function(event){
                  var key = event.keyCode;
                  //The key event will trigger for all keys but: Backspace, Delete, Left, Top, Right, Down, End, Home, PgUp, PgDown
                  if(key != 8 && key != 46 && key != 37 && key != 38 && key != 39 && key != 40 && key != 33 && key != 34 && key != 35 && key != 36){
                      if(this.value.length > totalCharacters){
                        this.value = this.value.substr(0, totalCharacters);
                        this.scrollTop = this.scrollHeight;
                      }
                      if(this.value.length == totalCharacters){
                        return false;
                      }
                  }
              });
              widget.keypress(function(){
                  var current_chars = this.value.length;
                  var left_chars = totalCharacters - current_chars;
                  current.text(current_chars);
                  left.text(left_chars);
              }).keypress();

              widget.keyup(function(){widget.keypress()});
          })();

      </script>';
      return $html.PHP_EOL.$js.PHP_EOL;

  }
}
